import { defineStore } from "pinia";
import type { NewCMSContent, VideoContent } from "@/common/type/cms/content";
import { store } from "@/store/store";

export const videoStore = defineStore("video", {
  state: (): { video: NewCMSContent; currentPlayer: PlayerState } => ({
    video:
      localStorage.getItem("video") === null
        ? {}
        : JSON.parse(localStorage.getItem("video")),
    currentPlayer:
      localStorage.getItem("currentPlayer") === null
        ? {}
        : JSON.parse(localStorage.getItem("currentPlayer"))
  }),
  getters: {
    getVideo(state) {
      return state.video;
    },
    getCurrentPlayer(state) {
      return state.currentPlayer;
    }
  },
  actions: {
    CHANGE_VIDEO(video: NewCMSContent) {
      this.video = video;
      localStorage.setItem("video", JSON.stringify(video));
    },
    CHANGE_CURRENT_PLAYER_TIME(time: number) {
      this.currentPlayer.time = time;
      localStorage.setItem(
        "currentPlayer",
        this.currentPlayer ? JSON.stringify(this.currentPlayer) : "{}"
      );
    },
    CHANGE_CURRENT_PLAYER(video: VideoContent) {
      this.currentPlayer = {
        time: 0,
        playing: true,
        video: video
      };
      localStorage.setItem(
        "currentPlayer",
        this.currentPlayer ? JSON.stringify(this.currentPlayer) : "{}"
      );
    }
  }
});

export function videoStoreHook() {
  return videoStore(store);
}
export type PlayerState = {
  time: number;
  playing: boolean;
  video: VideoContent;
};
